package com.androidservice.android.action;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FileDownServlet extends HttpServlet{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final String CONTENT_TYPE = "text/html; charset=GBK";

    //Initialize global variables
    public void init() throws ServletException {
    }
    
  //Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        response.setContentType(CONTENT_TYPE);
       
        String filename=new String(request.getParameter("filename").getBytes("iso-8859-1"),"gbk");
        File file=new File("F://book//WebRoot//"+filename);

        response.setContentType("application/x-msdownload");

        response.setContentLength((int)file.length());

       // response.setHeader("Content-Disposition","attachment;filename="+filename);
       
        response.setHeader("Content-Disposition","attachment;filename="+new String(filename.getBytes("gbk"),"iso-8859-1"));       

        FileInputStream fis=new FileInputStream(file);
        BufferedInputStream buff=new BufferedInputStream(fis);
        byte [] b=new byte[1024];
        long k=0;
        OutputStream myout=response.getOutputStream();
        while(k<file.length()){
            int j=buff.read(b,0,1024);
            k+=j;
            myout.write(b,0,j);

        }
        myout.flush();
    }
    
  //Process the HTTP Post request
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        doGet(request, response);
    }
}
